package user

import (
	"dustbe/database"
	"dustbe/util"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func ModifyUserInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	name := c.Query("name")
	imgUrl := c.Query("imgUrl")
	password := c.Query("password")
	newPassword := c.Query("newPassword")

	newHashedPassword := ""

	// 先判断有没有修改密码
	user, err := database.FindUserById(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "没有找到该用户"})
		return
	}
	ok := util.ValidRawPasswordCorrect(user.HashedPassword, password)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "原密码不对"})
		return
	}

	if len(newPassword) > 0 && newPassword != password {
		newHashedPassword, _  = util.Encrypte(newPassword)
	}

	user, err = database.ModifyUserInfo(id, name, newHashedPassword, imgUrl)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}
	user.HashedPassword = ""
	c.JSON(http.StatusOK, gin.H{"code": 200, "data": user})
}